<?php 
/*
 module:		用户管理
 create_time:	2024-03-12 15:43:18
 author:		
 contact:		
*/

namespace app\api\controller;

use app\api\service\MembersService;
use app\api\model\Members as MembersModel;
use EasyWeChat\Factory;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;

class Members extends Common {


	/**
	* @api {post} /Members/update 01、修改
	* @apiGroup Members
	* @apiVersion 1.0.0
	* @apiDescription  修改
	
	* @apiParam (输入参数：) {string}     		uid 主键ID (必填)

	* @apiHeader {String} Authorization 用户授权token
	* @apiHeaderExample {json} Header-示例:
	* "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"
	* @apiParam (输入参数：) {string}			last_login_time last_login_time 
	* @apiParam (输入参数：) {string}			reg_address reg_address 
	* @apiParam (输入参数：) {string}			reg_ip reg_ip 
	* @apiParam (输入参数：) {string}			reg_time reg_time 
	* @apiParam (输入参数：) {string}			pwd_hash pwd_hash 
	* @apiParam (输入参数：) {string}			password password 
	* @apiParam (输入参数：) {string}			mobile_audit mobile_audit 
	* @apiParam (输入参数：) {string}			mobile mobile 
	* @apiParam (输入参数：) {string}			email_audit email_audit 
	* @apiParam (输入参数：) {string}			email email 
	* @apiParam (输入参数：) {string}			name 姓名 
	* @apiParam (输入参数：) {string}			idcard 身份证号，目前是在线报名填入 
	* @apiParam (输入参数：) {string}			username username 
	* @apiParam (输入参数：) {string}			utype utype 
	* @apiParam (输入参数：) {string}			last_login_ip last_login_ip 
	* @apiParam (输入参数：) {string}			status status 
	* @apiParam (输入参数：) {string}			avatars avatars 
	* @apiParam (输入参数：) {string}			robot robot 
	* @apiParam (输入参数：) {string}			consultant consultant 
	* @apiParam (输入参数：) {string}			imei imei 
	* @apiParam (输入参数：) {string}			sms_num sms_num 
	* @apiParam (输入参数：) {string}			invitation_code invitation_code 
	* @apiParam (输入参数：) {string}			sitegroup_uid sitegroup_uid 
	* @apiParam (输入参数：) {string}			reg_source reg_source 
	* @apiParam (输入参数：) {string}			reg_source_cn reg_source_cn 
	* @apiParam (输入参数：) {string}			secretkey secretkey 
	* @apiParam (输入参数：) {string}			remind_sms_time remind_sms_time 
	* @apiParam (输入参数：) {string}			remind_sms_ex_time remind_sms_ex_time 
	* @apiParam (输入参数：) {string}			terminal terminal 
	* @apiParam (输入参数：) {string}			registration_id registration_id 
	* @apiParam (输入参数：) {string}			is_exsoliders 是否退役军人 1-否 2-是 
	* @apiParam (输入参数：) {string}			is_exsoliders_family 是否退役军人军属 1-否 2-是 
	* @apiParam (输入参数：) {string}			is_use_exsoliders 是否招聘退役军人 1-否 2-是 
	* @apiParam (输入参数：) {string}			is_exsoliders_create 是否是退役军人创业 1-否 2-是 
	* @apiParam (输入参数：) {string}			retireTime 退役时间 
	* @apiParam (输入参数：) {string}			token 人社的token 
	* @apiParam (输入参数：) {string}			member_type 求职群体  1普通   2退役军人   3军属 
	* @apiParam (输入参数：) {string}			wxapp_openid 微信小程序openid 

	* @apiParam (失败返回参数：) {object}     	array 返回结果集
	* @apiParam (失败返回参数：) {string}     	array.status 返回错误码  201
	* @apiParam (失败返回参数：) {string}     	array.msg 返回错误消息
	* @apiParam (成功返回参数：) {string}     	array 返回结果集
	* @apiParam (成功返回参数：) {string}     	array.status 返回错误码 200
	* @apiParam (成功返回参数：) {string}     	array.msg 返回成功消息
	* @apiSuccessExample {json} 01 成功示例
	* {"status":"200","msg":"操作成功"}
	* @apiErrorExample {json} 02 失败示例
	* {"status":" 201","msg":"操作失败"}
	*/
	function update(){
		$postField = 'uid,last_login_time,reg_address,reg_ip,reg_time,pwd_hash,password,mobile_audit,mobile,email_audit,email,name,idcard,username,utype,last_login_ip,status,avatars,robot,consultant,imei,sms_num,invitation_code,sitegroup_uid,reg_source,reg_source_cn,secretkey,remind_sms_time,remind_sms_ex_time,terminal,registration_id,is_exsoliders,is_exsoliders_family,is_use_exsoliders,is_exsoliders_create,retireTime,token,member_type,wxapp_openid';
		$data = $this->request->only(explode(',',$postField),'post',null);
		if(empty($data['uid'])){
			throw new ValidateException('参数错误');
		}
		$where['uid'] = $data['uid'];
		$res = MembersService::update($where,$data);
		return $this->ajaxReturn($this->successCode,'操作成功');
	}


 /*start*/
    /**
     * @api {post} /Members/upAvatars 05、修改头像

     */
    function upAvatars(){
        $postField = 'avatars';
        $data = $this->request->only(explode(',',$postField),'post',null);
        if(empty($data['avatars'])){
            throw new ValidateException('参数错误');
        }
        $where['uid'] =  $this->request->uid;
        $res = MembersService::upAvatars($where,$data);
        return $this->ajaxReturn($this->successCode,'操作成功');
    }
    /**
     * @api {get} /Members/view 02、查看详情
     */
    function view()
    {
        $uid  = $this->request->uid;
        $field = 'uid,last_login_time,reg_address,reg_ip,reg_time,pwd_hash,password,mobile_audit,mobile,email_audit,email,name,idcard,username,utype,last_login_ip,status,avatars,robot,consultant,imei,sms_num,invitation_code,sitegroup_uid,reg_source,reg_source_cn,secretkey,remind_sms_time,remind_sms_ex_time,terminal,registration_id,is_exsoliders,is_exsoliders_family,is_use_exsoliders,is_exsoliders_create,retireTime,token,member_type,wxapp_openid';
        $res = MembersModel::field($field)->where('uid',$uid)->findOrEmpty()->toArray();
        $res["apply_jobs_num"]= \app\api\model\Personaljobsapply::where("personal_uid",$uid)->count();//投递简历数量
        $res["collection_jobs_num"]=\app\api\model\Personalfavorites::where("personal_uid",$uid)->count();//收藏职位数量
        $res["collection_company_num"]=\app\api\model\Personalfocuscompany::where("uid",$uid)->count();//关注企业数量
        return $this->ajaxReturn($this->successCode, '返回成功', $res);
    }
    /**
     * @api {post} /Members/wxLogin 03、授权登录
     */
    function wxLogin()
    {
        $code = $this->request->post('code', '', null);
        if (empty($code)) $this->ajaxReturn($this->errorCode, '参数错误');
        $session = $this->getWxCode($code);
        if (empty($session["session_key"]) || empty($session["openid"])) $this->ajaxReturn($this->errorCode, '解析失败');
        $res = $this->getInfo(["wxapp_openid" => $session["openid"]]);
        if (empty($res)) {
            $res = ["uid" => 0];
        } else {
            $res["token"] = $this->setToken($res['uid']);
        }
        $res = array_merge($res, $session);
        return $this->ajaxReturn($this->successCode, '成功', $res);
    }

    /**
     * @api {post} /Members/mobileLogin 04、手机号授权登录
     */
    function mobileLogin()
    {
        $openid = $this->request->post('openid', '', null);
        $session_key = $this->request->post('session_key', '', null);
        $iv = $this->request->post('iv', '', null);
        $encrypted = $this->request->post('encrypted_data', '', null);
        if (empty($openid) || empty($session_key) || empty($iv) || empty($encrypted)) $this->ajaxReturn($this->errorCode, '参数错误');
        $phoneNumber = $this->getPhoneNumber($session_key, $iv, $encrypted);
        if (empty($phoneNumber)) $this->ajaxReturn($this->errorCode, '解析失败');

        $res = $this->getInfo(["mobile" => $phoneNumber]);
        if (empty($res)) {
            MembersModel::insertGetId(["mobile" => $phoneNumber,"username" => "用户".random(), "wxapp_openid" => $openid, "reg_time" => time()]);
        } else {
            MembersModel::where("uid", $res["uid"])->update(["mobile" => $phoneNumber, "wxapp_openid" => $openid]);
        }
        $res = $this->getInfo(["wxapp_openid" => $openid]);
        $res["token"] = $this->setToken($res['uid']);
        return $this->ajaxReturn($this->successCode, '成功', $res);
    }

    /**
     * 微信 code解析
     */
    function getWxCode($code)
    {

        $wxConfig = config("my.mini_program");
        $config = [
            'app_id' => $wxConfig['app_id'],
            'secret' => $wxConfig['secret'],
            'response_type' => 'array',
        ];
        $app = Factory::miniProgram($config);
        $session = $app->auth->session($code);
        return $session;
    }

    /**
     * 微信 手机号解析
     */
    function getPhoneNumber($session_key, $iv, $encrypted)
    {
        $wxConfig = config("my.mini_program");
        $phoneNumber = "";
        require __DIR__ . '/wxapp/wxBizDataCrypt.php';
        $pc = new \WXBizDataCrypt($wxConfig['app_id'], $session_key);
        $errCode = $pc->decryptData($encrypted, $iv, $data);
        if ($errCode == 0) {
            $data = json_decode($data, true);
            $phoneNumber = $data['phoneNumber'];
        }
        return $phoneNumber;
    }

    /**
     * 获取用户信息
     */
    function getInfo($where)
    {
        $field = 'uid,mobile,wxapp_openid';
        return MembersModel::field($field)->where($where)->findOrEmpty()->toArray();
    }
    /*end*/



}

